package com.yx.frame.http;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URLDecoder;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import com.yx.frame.authority.AuthorityManager;
import com.yx.frame.authority.User;
import com.yx.frame.log.LogFactory;
import com.yx.frame.log.LogWriter;
import com.yx.frame.service.Action;
import com.yx.frame.service.ActionManager;
import com.yx.frame.service.ServiceError;
import com.yx.frame.service.ServiceResult;
import com.yx.frame.util.SaveYhLogThread;


public final class HttpJsonRemoteServletJre6 extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -5970737286761194636L;
	static LogWriter log = LogFactory.getInstance().getLogWriter();
	static final String CONTENT_TYPE = "text/html; charset=utf-8";
	static final long postInputTimeout = 10 * 1000;
	
	public HttpJsonRemoteServletJre6() {
	}

	static final User getCurrentUser(JSONObject jsonObject, ServiceError error)
			throws Exception {
		String uID = null;
		try {
			uID = (String) jsonObject.get("UId");			
		} catch (Exception e) {
			error.setErrorMessage("非法的用户认证信息");
			return null;
		}
		return AuthorityManager.getInstance().authentication(uID, error);
	}
	static final ServiceResult getSystemActions(JSONObject requestJSONData,ServiceError error)throws Exception{
		ServiceResult returnObj = new ServiceResult();
		String isPerformanceMonitor="0";
		try{
			isPerformanceMonitor=requestJSONData.getString("IsPerformanceMonitor");
		}catch(Exception e){}
		if("1".equals(isPerformanceMonitor)){
			ActionManager.setPerformanceMonitor(true);	
		}else if("0".equals(isPerformanceMonitor)){
			ActionManager.setPerformanceMonitor(false);	
		}
		Action[] actionList=ActionManager.getInstace().listActions();
		JSONArray actionsJsonArray=new JSONArray();
		for(int i=0;i<actionList.length;i++){
			Action act=actionList[i];
			JSONObject row=new JSONObject();
			row.put("ID", act.getId());
			row.put("NAME", act.getName());
			row.put("COMMENT", act.getComment());
			row.put("TOTAL_TIME", act.getTotalAccessTime());
			row.put("TOTAL_ACCESS", act.getTotalAccessNumber());
			actionsJsonArray.put(row);
		}
		returnObj.put("ACTIONS", actionsJsonArray);
		return returnObj;
    }
	public final void doPost(HttpServletRequest request,HttpServletResponse response) {
		long beginTime = System.currentTimeMillis();
		JSONObject jsonObject =null;
		ServiceError error = new ServiceError();
		boolean asyncService =false;
		try {			
			jsonObject = readRequest(request,error);
			/*HttpSession session = request.getSession();
			if(session != null && session.getAttribute("SESSION_CERTCODE") != null){
				JSONObject requestJSONData = jsonObject.getJSONObject("RequestData");
				requestJSONData.put("SESSION_CERTCODE", session.getAttribute("SESSION_CERTCODE"));
			}*/
			if (error.isError())throw new Exception(error.getErrorMessage());
//			asyncService = jsonObject.getBoolean("AsyncService");
		}catch (Throwable e) {
			error.setErrorMessage(e.getMessage());
			writeResponse(response, error);
			return;
		}
		handler(false,jsonObject,error,response,beginTime);		
	}
	
	
	public static final void handler(boolean asyncService,JSONObject jsonObject,ServiceError error,HttpServletResponse response,long beginTime) {
		int action = -1;
		String serviceName = null;
		User user=null;
		try {
			action = Integer.parseInt(String.valueOf(jsonObject.get("ActionId")));
			user = getCurrentUser(jsonObject, error);
			if (error.isError())return;
			ServiceResult returnJsonObject=null;
			if(action>=0){
				JSONObject requestJSONData = jsonObject.getJSONObject("RequestData");
				Action permitAction = user.getPermitedAction(action, error);
				if (error.isError())return;
				/*//操作日志
                SaveYhLogThread thread = new SaveYhLogThread(user.getUserId(), user.getUserName(),permitAction.getMethod(), 
                        permitAction.getComment(), requestJSONData.toString(), "WXBS","");
                thread.start();*/
				
				serviceName =  permitAction.getService() + "/" + permitAction.getMethod();
				returnJsonObject = permitAction.doActionMethod(user, requestJSONData, error);
			}else{
				JSONObject requestJSONData = jsonObject.getJSONObject("RequestData");							
				returnJsonObject=getSystemActions(requestJSONData,error);
			}			
			if(!error.isError()){
				debug(user, serviceName, "返回JSON:" + returnJsonObject);
				writeResponse(response, returnJsonObject);			
			}
		} catch (Throwable e) {
			//e.printStackTrace();
			error.setErrorMessage(e.getMessage());			
		}finally {
			if (error.isError()){
				error(user, serviceName, "返回JSON:" + error);
				writeResponse(response, error);
			}
			debug(user, serviceName, "服务异步执行（"+asyncService+"）,耗时：" + (System.currentTimeMillis() - beginTime)	+ "毫秒！");
		}
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		writeResponse(response, new ServiceError("不支持GET请求"));
	}

	public static JSONObject readRequest(HttpServletRequest request,
			ServiceError error) throws Exception {
		String s = null;
		StringBuffer sb = new StringBuffer();
		long t = System.currentTimeMillis();
		BufferedReader br = new BufferedReader(new InputStreamReader(
				request.getInputStream()));
		while ((s = br.readLine()) != null) {
			//sb.append(new String(s.getBytes("GBK"),"utf-8"));
			s = URLDecoder.decode(s,"UTF-8");
			sb.append(s);
			if (System.currentTimeMillis() - t > postInputTimeout) {
				br.close();
				error.setErrorMessage("请求超时");
				return null;
			}
		}
		br.close();
		String inJesonStr = sb.toString();
		debug(null, "AJAX Service", "收到请求:" + inJesonStr);
		JSONObject jsonObject = new JSONObject(inJesonStr);
		return jsonObject;
	}

	public static void writeResponse(HttpServletResponse response,
			ServiceResult serviceResult) {
		try {
			response.setContentType(CONTENT_TYPE);
			// response.setContentType("<meta http-equiv=\"Access-Control-Allow-Origin\" content=\"*\">");
			response.setHeader("Access-Control-Allow-Origin", "*");
			PrintWriter out = response.getWriter();
			if (serviceResult == null) {
				ServiceError error = new ServiceError("返回为空");
				out.println(error.toString());
			} else {
				out.println(serviceResult.toString());
			}
			out.flush();
			out.close();
		} catch (Exception e) {			
		}
	}
	public static void error(User user, String serviceName, String logMsg) {
		log.error(user, serviceName, logMsg);
	}

	public static void debug(User user, String serviceName, String logMsg) {
		log.debug(user, serviceName, logMsg);
	}
}
